# -*- coding: utf-8 -*-

from machine import Pin

from MsgProcess import MsgProcess


class Led(MsgProcess):
    def __init__(self):
        super().__init__()
        self.led_gpio = 22
        self.button_gpio = 13
        self.butt_status = -1
        self.led_Pin = None

    def Start(self, message=None):
        print('进入Led插件了')
        self.led()
        self.button()

    # ===== 点灯事件 Start =======
    def led(self, gpio='', state=None):
        if str(gpio) != "" and int(self.led_gpio) != int(gpio):
            self.led_gpio = int(gpio)
            self.led_Pin = None

        if self.led_Pin is None:
            self.led_Pin = Pin(self.led_gpio, Pin.OUT)

        if state==1:
            self.led_Pin.off()
            self.led_state = 1
        elif state==0:
            self.led_Pin.on()
            self.led_state = 0
        else:
            self.led_state = 0 if int(self.led_Pin.value()) == 1 else 1
        self.send(Data={'type':'led','state': self.led_state})

    # 按钮事件
    def button(self):
        def key_run(e):
            if self.butt_status != e.value():
                self.butt_status = e.value()
                self.send(Data={'type':'button','state': self.butt_status})

        button_pin = Pin(self.button_gpio, Pin.IN)
        button_pin.irq(trigger=Pin.IRQ_FALLING, handler=key_run)

    def Text(self, message):
        Data = message['Data']

        # 点灯事件，消息体：{'type': 'led', 'state': 1/0, 'pin': 引脚(可留空)}
        if 'type' in dict(Data) and Data['type'] == 'led':
            state = Data['state'] if 'state' in dict(Data) else ''
            gpio = Data['pin'] if 'pin' in dict(Data) else ''
            self.led(gpio, state)

